package com.miplus.ccrm.core.service.action;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import com.miplus.ccrm.core.controller.vo.action.*;
import com.miplus.ccrm.core.controller.vo.conf.WfNextStepVo;
import com.miplus.ccrm.core.controller.vo.credit.CrdCmdResVo;
import com.miplus.ccrm.core.mapper.ConCustomerMapper;
import com.miplus.ccrm.core.mapper.FiCreditcasesMapper;
import com.miplus.ccrm.core.pojo.*;
import com.miplus.ccrm.core.mapper.FiDeductMapper;
import com.miplus.ccrm.core.service.FiWorkFlowCase;
import com.miplus.ccrm.core.service.conf.MsgAlertsService;
import com.miplus.ccrm.core.service.crd.CrdCommand;
import com.miplus.ccrm.core.service.crd.CreditCardService;
import com.miplus.ccrm.core.service.crd.FiTaskService;
import com.miplus.ccrm.core.service.strategy.CpCalllistService;
import com.miplus.ccrm.core.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
* @author pc
* @description 针对表【fi_deduct(划扣申请表)】的数据库操作Service实现
* @createDate 2024-04-24 19:18:31
*/
@Slf4j
@Service
public class FiDeductServiceImpl extends MPJBaseServiceImpl<FiDeductMapper, FiDeduct>
    implements FiDeductService{

    @Resource
    private FiTaskService fiTaskService;
    @Resource
    private CpCalllistService cpCalllistService;
    @Resource
    private FiWorkFlowCase fiWorkFlowCase;
    @Resource
    private MsgAlertsService msgAlertsService;
    @Resource
    private FiCreditcasesMapper fiCreditcasesMapper;
    @Resource
    private ConCustomerMapper conCustomerMapper;
    @Resource
    private CreditCardService creditCardService;

    @Override
    public IPage<FiDedResVo> fiDeductList(String $usrid, FiApplyReqVo paras)
    {
        return selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                FiDedResVo.class,
                new MPJLambdaWrapper<FiDeduct>()
                        .selectAs("fun_getnames('FI.DEDUCT.STATUS',t.status)", FiDedResVo::getStatusdsc)
                        .selectAs("fun_getnames('FI.DEDUCT.REASON',t.applyreason)", FiDedResVo::getApplyreason)
                        .selectAs("(select cl.wfid from cp_calllist cl where cl.clid=t.clid)", FiDedResVo::getWfid)
                        .selectAs("(select g.GRPNAME from sys_user u join sys_grp g on u.GROUPS=g.GRPID where u.USRID=t.applyusr)",FiDedResVo::getApplygrp)
                        .selectAll(FiDeduct.class)
                        .apply("fc_hasApplyView(t.applynumber,'SYS_CARDDED',t.applyusr,{0},t.status,t.confirmusr)>0",$usrid)
                        .apply(JPubUtils.IsNotEmpty(paras.getApplygrp()),"fc_hasUsrInGroup(t.applyusr,{0})>0",paras.getApplygrp())
                        .eq(JPubUtils.IsNotEmpty(paras.getFicaseid()), FiDeduct::getFicaseid,paras.getFicaseid())
                        .eq(JPubUtils.IsNotEmpty(paras.getStatus()),FiDeduct::getStatus,paras.getStatus())
                        .eq(JPubUtils.IsNotEmpty(paras.getApplyusr()),FiDeduct::getApplyusr,paras.getApplyusr())
                        .between(JPubUtils.IsNotEmpty(paras.getStartdt()), FiDeduct::getApplydt,JPubUtils.StringToDate(paras.getStartdt()),JPubUtils.StringToDate(paras.getEnddt()))
        );
    }

    @Override
    @Transactional
    public CmdResVo fiDeductAdd(String $usrid, FiDedAddVo paras)
    {
        //1=待审核
        List<FiDeduct> fiDeducts=selectJoinList(FiDeduct.class,
                new MPJLambdaWrapper<FiDeduct>()
                        .eq(FiDeduct::getFicaseid,paras.getFicaseid())
                        .in(FiDeduct::getStatus,
                                EnumConfirmStatus.New.value,EnumConfirmStatus.Pending.value,
                                EnumConfirmStatus.Process.value)
        );
        //相同的案件正在审核中
        if(JPubUtils.IsNotEmpty(fiDeducts)){
            throw new ServiceException(EnumRCode.DataProcess.value, EnumRCode.DataProcess.name);
        }
        String clid=paras.getClid();
        if(JPubUtils.IsEmpty(clid)){
            clid="SYS_CARDDED"; //此任务是系统配置任务，不能delete
        }

        FiCreditcases creditcases=fiCreditcasesMapper.selectById(paras.getFicaseid());
        ConCustomer customer=conCustomerMapper.selectById(creditcases.getCustomernumber());
        //客户端传过来的借记卡可能是带星加密的
        String cardno=customer.getDebitcardno();
        String crdcardno=creditCardService.getAccOpenLastCardNo(creditcases.getCreditAcct());
        Integer wfid=cpCalllistService.getCalllistWfID(clid);

        int tasknumber=fiTaskService.addTask($usrid,clid,paras.getFicaseid(), EnumFiChannel.Deduction.value);

        int ret=0;
        log.info("applyAdd:clid={},ficase={},tasknumber={},wfid={}",clid,paras.getFicaseid(),tasknumber,wfid);

        FiDeduct fi = new FiDeduct();
        fi.setClid(clid);
        fi.setApplyreason(paras.getApplyreason());
        fi.setFicaseid(paras.getFicaseid());
        fi.setApplydsc(paras.getApplydsc());
        fi.setTasknumber(tasknumber);
        fi.setCardno(cardno);
        fi.setCrdcardno(crdcardno);
        fi.setAmount(paras.getAmount());
        fi.setStatus(EnumConfirmStatus.New.value); //新建
        fi.setApplydt(new Date());
        fi.setApplyusr($usrid);
        ret=baseMapper.insert(fi);

        int applynumber=fi.getApplynumber();

        if(wfid>0){
            //wfid=0 表示此任务clid没有配置工作流，前台可以根据是否有wfid显示不通的审批流程或状态
            String status=fiWorkFlowCase.doCreate($usrid,wfid,applynumber,tasknumber);
            fi = new FiDeduct();
            fi.setApplynumber(applynumber);
            fi.setStatus(Integer.parseInt(status)); //处理中
            baseMapper.updateById(fi);
        }

        return new CmdResVo(ret,Integer.toString(applynumber));
    }

    @Override
    public CmdResVo fiDeductCancel(String $usrid, FiApplyCancelVo paras)
    {
        FiDeduct fi=baseMapper.selectById(paras.getApplynumber());
        if(JPubUtils.IsNotEmpty(fi.getTasknumber())){
            fiTaskService.updateStatus(fi.getTasknumber(),$usrid,"X");
        }
        else{
            log.warn("applyCancel:getTasknumber.isnull");
        }
        Integer wfid=cpCalllistService.getCalllistWfID(fi.getClid());
        fiWorkFlowCase.doCancel($usrid,wfid,fi.getApplynumber());

        fi = new FiDeduct();
        fi.setApplynumber(paras.getApplynumber());
        fi.setStatus(EnumConfirmStatus.Cancel.value); //取消
        fi.setCancelusr($usrid);
        fi.setCanceldt(new Date());
        int ret=baseMapper.updateById(fi);

        return new CmdResVo(ret,fi.getApplynumber().toString());
    }

    @Override
    public CmdResVo fiDeductConfirm(String $usrid, FiApplyConfirmVo paras)
    {
        boolean confirmend=true;
        String okstatus=paras.getActionid().toString();
        FiDeduct fiDeduct=baseMapper.selectById(paras.getApplynumber());
        if(JPubUtils.IsNotEmpty(paras.getCaseactid())){
            //需要走工作流
            WfNextStepVo wfNextStepVo=fiWorkFlowCase.doExec($usrid,paras.getCaseactid(),
                    paras.getActionid(),paras.getWfcaseid(),paras.getConfirmdsc()
            );
            okstatus=wfNextStepVo.getStatus();

            //可能有多级审核,3=审核全部完成
            if(!JPubUtils.IsEqual(wfNextStepVo.getType(), EnumWorkFlowStep.End.value)) {
                confirmend=false;
            }
        }
        else{
            Integer wfid=cpCalllistService.getCalllistWfID(fiDeduct.getClid());
            if(wfid==null||wfid==0){//不使用工作流,这种情况下okstatus就是字典ID，直接写审核结果
                log.info("fiDeductConfirm.nouse workflow：okstatus={}",okstatus);
            }
            else{//可能配置错误或网络引起的，2024-08-29
                log.warn("fiDeductConfirm.nofind wf caseactid.");
                throw new ServiceException(EnumRCode.WfDataErr.value, EnumRCode.WfDataErr.name);
            }
        }

        //单纯就是审批流程，结果后续操作就在这里写，如果有后续反馈的，在result里面写，比如外访
        if(JPubUtils.IsNotEmpty(fiDeduct.getTasknumber())&&confirmend) {
            fiTaskService.updateStatus(
                    fiDeduct.getTasknumber(),
                    $usrid,
                    fiWorkFlowCase.getPassStatus(okstatus)
            );

            msgAlertsService.msgAlertAdd(EnumFiChannel.Deduction,
                    fiDeduct.getApplyusr(),
                    $usrid,
                    EnumUtil.ConfirmStatusName(okstatus)
            );

            if(JPubUtils.IsEqual(okstatus,EnumConfirmStatus.Pass.value)) {//审核通过
                CrdCmdResVo resVo=CrdCommand.crdCarDeduction(
                        fiDeduct.getCardno(),
                        fiDeduct.getCrdcardno(),
                        fiDeduct.getAmount()
                );
                EnumTaskStatus enumTaskStatus=EnumTaskStatus.F;
                if(JPubUtils.IsEqual(resVo.getRespCode(),"0")){
                    enumTaskStatus=EnumTaskStatus.R;
                }
                fiTaskService.updateStatus(
                        fiDeduct.getTasknumber(),
                        $usrid,
                        enumTaskStatus.toString()
                );
                msgAlertsService.msgAlertAdd(EnumFiChannel.Deduction,
                        fiDeduct.getApplyusr(),
                        $usrid,
                        enumTaskStatus.name
                );
            }
        }

        FiDeduct fi = new FiDeduct();
        fi.setApplynumber(paras.getApplynumber());
        fi.setStatus(Integer.parseInt(okstatus));
        fi.setConfirmusr($usrid);
        fi.setConfirmdt(new Date());
        fi.setConfirmdsc(paras.getConfirmdsc());
        int ret=baseMapper.updateById(fi);

        return new CmdResVo(ret,paras.getApplynumber().toString());
    }
}




